/**查找分页控件 -> 请求下一页 -> 增删元素 -> 加载在页面 */
async function loadNextPage() {
  let [lastNrPage] = [...document.querySelectorAll('.read_btn')].slice(-1)
  let url = lastNrPage.querySelector('a:nth-of-type(4)').href

  const response = await fetch(url)
  const decoder = new TextDecoder('utf8')
  const html = decoder.decode(await response.arrayBuffer())
  let div = document.createElement('div')
  div.innerHTML = html

  let alink = document.createElement('a')
  alink.href = url
  alink.innerText = '本页'
  div.querySelectorAll('.read_btn').forEach((pageDom) => {
    pageDom.insertBefore(alink.cloneNode(true), pageDom.children[2])
    pageDom.removeChild(pageDom.children[3])
  })

  let containerDom = div.querySelector('.word_read')
  containerDom.style.width = '100%'

  let rowDetail = div.querySelector('.container .row.row-detail')
  rowDetail.style.marginTop = '0'

  let layout = div.querySelector('.container .layout.layout-col1')
  layout.style.margin = '0'
  layout.style.borderLeft = 'none'
  layout.style.borderRight = 'none'
  layout.style.borderBottom = 'none'

  cleanPage(div)

  let [lastContent] = [...document.querySelectorAll('.word_read')].slice(-1)
  lastContent.parentNode.appendChild(div)
  return { div, url }
}

/**从页面获取书名 */
function getBookName() {
  let el = document.querySelector('.layout-tit a:nth-child(2)')
  return el ? el.innerText : ''
}

/**_addObserver传入targetSelector、chapterTitleSelector*/
function addObserver(dom = document, url = location.href) {
  _addObserver('.word_read', '.word_read>h3:nth-child(1)', dom, url)
}

/**包装cleanPage方法 */
function cleanPage(context = document) {
  $chromePlugin.cleanPage(context, [
    '.header',
    '.nav',
    '.container .layout h2.layout-tit',
    '.topbar',
    '.novel_chapter>p[style="font-size:12px;"]',
    '.word_read>p[style="font-size:12px;"]',
    '.novel_chapter>.row',
    '.container>.row.row-section',
    '.footer',
  ])
}

$chromePlugin.loadQueueFn.push(cleanPage)
